package com.mimosa.common.system.permission;

import java.awt.MenuItem;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.mimosa.common.dao.HibernateDao;

@Repository
public class TPermissionDao extends HibernateDao<TPermission, String> {

	public List<TPermission> getPerByRid2type(String rid, String itemType) {
		Criterion ucriterion = Restrictions.eq("roleOrUserId", rid);
		Criterion icriterion = Restrictions.eq("itemType", itemType); // 1
		return this.find(ucriterion, icriterion);
	}

	public List<String> getItemByRid2type(String roleid, String itemType) {
		return this.find("select r.itemId from TPermission r where r.roleOrUserId =? and r.itemType =? ", roleid,
				itemType);
	}

	/**
	 * 根据用户id获取所有的权限ids
	 * 
	 * @param userid
	 *            用户id
	 * @param ordinal
	 *            权限类型
	 * @return
	 */
	public List<String> getItemByUid2type(String userid, String itemType) {
		return this
				.find("select distinct(r.itemId) from TPermission r where  r.itemType = ? and (r.roleOrUserId=? or r.roleOrUserId in "
						+ "(select u.roleId from TUserRole u where u.userId = ?))", itemType, userid, userid);
	}

	public List<TPermission> getByUid2type(String userid, String itemType) {
		return this.find("from TPermission r where  r.itemType = ? and  (r.roleOrUserId=? and r.roleOrUserId in "
				+ "(select u.roleId from TUserRole u where u.userId = ?))", itemType, userid, userid);
	}

	/**
	 * 根据用户id获取所有的权限ids
	 * 
	 * @param userid
	 *            用户id
	 * @param ordinal
	 *            权限类型
	 * @return
	 */
	public List<MenuItem> getItemByUid2Manager(String userid, String idPrefix, String itemType) {
		return this.find(
				"from MenuItem m where m.id in (select distinct(r.itemId) from TPermission r where  r.itemType = ? and r.itemId like ? and  (r.roleOrUserId=? OR r.roleOrUserId in "
						+ "(select u.roleId from TUserRole u where u.userId = ?)))",
				itemType, idPrefix + "%", userid, userid);
	}

	/**
	 * 删除指这类型的权限信息
	 * 
	 * @param itemId
	 * @param permissionType
	 */
	public void deletePermissionByType(String itemId, PermissionType permissionType) {
		Query query = this.createQuery("DELETE FROM TPermission where itemId=? and itemType=?", itemId,
				permissionType.name());
		query.executeUpdate();
	}

	/**
	 * 删除指这类型的权限信息
	 * 
	 * @param itemId
	 * @param permissionType
	 */
	public void deleteByCompositeKey(String itemId, String roleOrUserId) {
		Query query = this.createQuery("DELETE FROM TPermission where itemId=? and roleOrUserId=?", itemId,
				roleOrUserId);
		query.executeUpdate();
	}
}
